import React, { useState, useEffect } from "react";
import { 
  Card, 
  Row, 
  Col, 
  Tag, 
  Button, 
  Space, 
  Typography, 
  Descriptions, 
  Table, 
  Progress,
  Statistic,
  Divider,
  Alert,
  Tabs,
  List,
  Avatar,
  Badge
} from "antd";
import { 
  BookOutlined, 
  TeamOutlined, 
  CalendarOutlined, 
  UserOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  SettingOutlined,
  FileTextOutlined,
  MessageOutlined
} from "@ant-design/icons";
import { useParams, useNavigate } from "react-router-dom";
import { COURSES, CLASSES, generateStudents } from "../../../utils/mockData";

const { Title, Text } = Typography;
const { TabPane } = Tabs;

interface CourseDetail {
  id: string;
  name: string;
  code: string;
  description: string;
  category: string;
  credits: number;
  hours: number;
  semester: string;
  location: string;
  schedule: string;
  maxStudents: number;
  currentStudents: number;
  status: string;
  createTime: string;
  teacher: {
    id: string;
    name: string;
    title: string;
  };
  classes: Array<{
    id: string;
    name: string;
    code: string;
    studentCount: number;
  }>;
}

interface Student {
  id: string;
  name: string;
  studentNumber: string;
  major: string;
  grade: string;
  avatar: string;
  status: string;
  enrollTime: string;
}

const CourseDetail: React.FC = () => {
  const { courseId } = useParams<{ courseId: string }>();
  const navigate = useNavigate();
  
  const [courseDetail, setCourseDetail] = useState<CourseDetail | null>(null);
  const [students, setStudents] = useState<Student[]>([]);
  const [loading, setLoading] = useState(true);

  // 使用统一的课程详情数据
  useEffect(() => {
    // 根据courseId查找对应的课程
    const course = COURSES.find(c => c.id === courseId) || COURSES[0];
    
    const courseDetail: CourseDetail = {
      id: course.id,
      name: course.name,
      code: course.code,
      description: course.description,
      category: "必修",
      credits: course.credits,
      hours: course.credits * 16, // 每学分16学时
      semester: course.semester,
      location: course.location,
      schedule: course.schedule,
      maxStudents: course.maxStudents,
      currentStudents: course.currentStudents,
      status: course.status,
      createTime: course.createTime,
      teacher: {
        id: course.teacher.id,
        name: course.teacher.name,
        title: course.teacher.title
      },
      classes: course.classIds.map(classId => {
        const cls = CLASSES.find(c => c.id === classId);
        return {
          id: cls?.id || classId,
          name: cls?.name || "未知班级",
          code: cls?.code || "UNKNOWN",
          studentCount: cls?.studentCount || 0
        };
      })
    };

    // 生成该课程的所有学生数据
    const allStudents: Student[] = [];
    let studentIndex = 0;
    
    course.classIds.forEach(classId => {
      const cls = CLASSES.find(c => c.id === classId);
      if (cls) {
        const students = generateStudents(cls.studentCount, cls.major, cls.grade, studentIndex);
        allStudents.push(...students);
        studentIndex += cls.studentCount;
      }
    });

    setTimeout(() => {
      setCourseDetail(courseDetail);
      setStudents(allStudents);
      setLoading(false);
    }, 1000);
  }, [courseId]);

  const studentColumns = [
    {
      title: "学生信息",
      key: "info",
      render: (record: Student) => (
        <Space>
          <Avatar src={record.avatar} />
          <div>
            <div>{record.name}</div>
            <Text type="secondary">{record.studentNumber}</Text>
          </div>
        </Space>
      )
    },
    {
      title: "专业",
      dataIndex: "major",
      key: "major"
    },
    {
      title: "年级",
      dataIndex: "grade",
      key: "grade"
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => (
        <Badge 
          status={status === "active" ? "success" : "default"} 
          text={status === "active" ? "在读" : "退课"}
        />
      )
    },
    {
      title: "选课时间",
      dataIndex: "enrollTime",
      key: "enrollTime"
    },
    {
      title: "操作",
      key: "action",
      render: () => (
        <Space>
          <Button type="link" size="small">查看详情</Button>
          <Button type="link" size="small" danger>移除</Button>
        </Space>
      )
    }
  ];

  if (loading) {
    return (
      <div style={{ padding: 24, textAlign: 'center' }}>
        <div>加载中...</div>
      </div>
    );
  }

  if (!courseDetail) {
    return (
      <div style={{ padding: 24 }}>
        <Alert
          message="课程不存在"
          description="您访问的课程不存在或已被删除"
          type="error"
          showIcon
          action={
            <Button size="small" onClick={() => navigate("/teacher/courses")}>
              返回课程列表
            </Button>
          }
        />
      </div>
    );
  }

  return (
    <div style={{ padding: 24 }}>
      {/* 页面头部 */}
      <Card>
        <Row justify="space-between" align="middle">
          <Col>
            <Title level={2} style={{ margin: 0 }}>
              {courseDetail.name}
            </Title>
            <Text type="secondary">{courseDetail.code}</Text>
          </Col>
          <Col>
            <Space>
              <Button icon={<EditOutlined />}>
                编辑课程
              </Button>
              <Button icon={<SettingOutlined />}>
                课程设置
              </Button>
              <Button type="primary" icon={<PlusOutlined />}>
                添加学生
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 课程概览 */}
      <Row gutter={16} style={{ marginTop: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="选课人数"
              value={courseDetail.currentStudents}
              suffix={`/ ${courseDetail.maxStudents}`}
              prefix={<TeamOutlined />}
            />
            <Progress 
              percent={Math.round((courseDetail.currentStudents / courseDetail.maxStudents) * 100)} 
              size="small"
              style={{ marginTop: 8 }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="课程学分"
              value={courseDetail.credits}
              suffix="学分"
              prefix={<BookOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="课程学时"
              value={courseDetail.hours}
              suffix="学时"
              prefix={<CalendarOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="授课班级"
              value={courseDetail.classes.length}
              suffix="个班级"
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 主要内容区域 */}
      <Row gutter={16} style={{ marginTop: 16 }}>
        <Col span={16}>
          <Card>
            <Tabs defaultActiveKey="overview">
              <TabPane 
                tab={
                  <span>
                    <BookOutlined />
                    课程概览
                  </span>
                } 
                key="overview"
              >
                <Descriptions title="课程基本信息" bordered column={2}>
                  <Descriptions.Item label="课程名称">{courseDetail.name}</Descriptions.Item>
                  <Descriptions.Item label="课程代码">{courseDetail.code}</Descriptions.Item>
                  <Descriptions.Item label="课程类别">
                    <Tag color="blue">{courseDetail.category}</Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="课程状态">
                    <Tag color={courseDetail.status === "active" ? "green" : "red"}>
                      {courseDetail.status === "active" ? "进行中" : "已结束"}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="开课学期">{courseDetail.semester}</Descriptions.Item>
                  <Descriptions.Item label="上课地点">{courseDetail.location}</Descriptions.Item>
                  <Descriptions.Item label="上课时间">{courseDetail.schedule}</Descriptions.Item>
                  <Descriptions.Item label="授课教师">{courseDetail.teacher.name}</Descriptions.Item>
                  <Descriptions.Item label="课程描述" span={2}>
                    {courseDetail.description}
                  </Descriptions.Item>
                </Descriptions>

                <Divider />

                <Title level={4}>授课班级</Title>
                <Row gutter={16}>
                  {courseDetail.classes.map(cls => (
                    <Col span={8} key={cls.id}>
                      <Card size="small" style={{ marginBottom: 8 }}>
                        <div>
                          <Text strong>{cls.name}</Text>
                          <br />
                          <Text type="secondary">{cls.code}</Text>
                          <br />
                          <Tag color="blue">{cls.studentCount}人</Tag>
                        </div>
                      </Card>
                    </Col>
                  ))}
                </Row>
              </TabPane>

              <TabPane 
                tab={
                  <span>
                    <TeamOutlined />
                    学生管理
                  </span>
                } 
                key="students"
              >
                <div style={{ marginBottom: 16 }}>
                  <Space>
                    <Button type="primary" icon={<PlusOutlined />}>
                      添加学生
                    </Button>
                    <Button icon={<FileTextOutlined />}>
                      导出名单
                    </Button>
                    <Button icon={<MessageOutlined />}>
                      发送通知
                    </Button>
                  </Space>
                </div>
                <Table
                  columns={studentColumns}
                  dataSource={students}
                  rowKey="id"
                  pagination={{
                    total: students.length,
                    pageSize: 10,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共 ${total} 名学生`,
                  }}
                />
              </TabPane>

              <TabPane 
                tab={
                  <span>
                    <CalendarOutlined />
                    课程安排
                  </span>
                } 
                key="schedule"
              >
                <Alert
                  message="课程时间安排"
                  description={`${courseDetail.schedule} | ${courseDetail.location}`}
                  type="info"
                  showIcon
                  style={{ marginBottom: 16 }}
                />
                
                <Card title="课程日历" size="small">
                  <div style={{ textAlign: 'center', padding: 40, color: '#999' }}>
                    课程日历功能开发中...
                  </div>
                </Card>
              </TabPane>

              <TabPane 
                tab={
                  <span>
                    <FileTextOutlined />
                    课程资源
                  </span>
                } 
                key="resources"
              >
                <div style={{ textAlign: 'center', padding: 40, color: '#999' }}>
                  课程资源管理功能开发中...
                </div>
              </TabPane>
            </Tabs>
          </Card>
        </Col>

        <Col span={8}>
          {/* 快速操作 */}
          <Card title="快速操作" style={{ marginBottom: 16 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <Button block icon={<PlusOutlined />}>
                添加学生
              </Button>
              <Button block icon={<FileTextOutlined />}>
                上传课件
              </Button>
              <Button block icon={<MessageOutlined />}>
                发送通知
              </Button>
              <Button block icon={<CalendarOutlined />}>
                安排考试
              </Button>
            </Space>
          </Card>

          {/* 课程统计 */}
          <Card title="课程统计">
            <List size="small">
              <List.Item>
                <Text>选课人数</Text>
                <Text strong>{courseDetail.currentStudents}/{courseDetail.maxStudents}</Text>
              </List.Item>
              <List.Item>
                <Text>班级数量</Text>
                <Text strong>{courseDetail.classes.length}个</Text>
              </List.Item>
              <List.Item>
                <Text>课程状态</Text>
                <Tag color={courseDetail.status === "active" ? "green" : "red"}>
                  {courseDetail.status === "active" ? "进行中" : "已结束"}
                </Tag>
              </List.Item>
              <List.Item>
                <Text>创建时间</Text>
                <Text>{courseDetail.createTime}</Text>
              </List.Item>
            </List>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default CourseDetail; 
 
 
 
 